package com.kuang.blog.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuang.blog.entity.User;
import com.kuang.blog.exception.AllException;
import com.kuang.blog.service.UserService;
import com.kuang.blog.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;

@Component
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private JwtUtils jwtUtils;


    /**
     * 授权 获取用户的角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        {
            System.out.println("shiro流程5/5===AuthRealm===doGetAuthorizationInfo");
            //1. 从 PrincipalCollection 中来获取登录用户的信息
            User user = (User) principals.getPrimaryPrincipal();
            //Integer userId = user.getUserId();
            //2.添加角色和权限
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addStringPermission(user.getPermissions());
            return simpleAuthorizationInfo;

        }
    }

    /**
     * 认证功能：就是将token封存的账号密码重新验证
     *
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("shiro流程5/4===AuthRealm===doGetAuthenticationInfo");
        //获取token，既前端传入的toke
        String jwtToken = (String) token.getPrincipal();
        Claims claims = jwtUtils.decodeJwt(jwtToken);
        Object username = claims.get("username");
        Object password = claims.get("password");
        String id = claims.getId();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username", username);
        //1. 根据accessToken，查询用户信息
        User getUser = userService.getOne(queryWrapper);
        //正确
        if (getUser.getUsername().equals(username) && getUser.getPassword().equals(password)) {
            //5. 此处的 SimpleAuthenticationInfo 可返回任意值，因为我们密码校验时不会用到它
            return new SimpleAuthenticationInfo(getUser, jwtToken, this.getName());
        } else {
            throw new AllException("token错误");
        }

    }
}
